package com.mimc.framework.interceptors;

import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.mimc.common.constant.AppConstants;
import com.mimc.common.constant.WebConstants;
import com.mimc.common.exception.ServiceException;
import com.mimc.common.utils.StringUtils;
import com.mimc.core.model.ImUser;
import com.mimc.framework.jwt.ApiTokenUtils;
import io.jboot.Jboot;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class ApiJwtInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation invocation) {
        String action=invocation.getActionKey();
        log.info("当前访问路径：{}",action);
        if(action.startsWith("/api")){
            List<String> strs=new ArrayList<String>(Arrays.asList("/api/index/**"));
            if(StringUtils.matches(action,strs)){
                invocation.invoke();
                return;
            }
            String jwtkey = Jboot.configValue("yminfo.jwtkey");
            String token=invocation.getController().getHeader("token");
            //执行认证
            if (StrUtil.isBlank(token)){
                throw new ServiceException("无token，请重新登录！", AppConstants.CODE_401);
            }
            try {
                if(!ApiTokenUtils.verifyToken(token,jwtkey)){
                    throw new ServiceException("token验证失败，请重新登录！", AppConstants.CODE_401);
                }
            }catch (Exception e){
                throw new ServiceException(e.getMessage(), AppConstants.CODE_401);
            }
            Long userId=ApiTokenUtils.getCurrentUserId();
            if(userId==null){
                throw new ServiceException("token验证失败，请重新登录！", AppConstants.CODE_401);
            }
            ImUser user=ApiTokenUtils.getCurrentUser();
            if(user==null){
                throw new ServiceException("用户不存在，请重新登录！", AppConstants.CODE_401);
            }
            invocation.getController().getRequest().setAttribute(WebConstants.REQUEST_IM_USER,user);
            invocation.invoke();
        }else {
            invocation.invoke();
        }
    }
}
